import request from '../utils/request'

export function getPostObjectSignedUrl (object, type) {
  return request({
    url: 'oss/post-object',
    method: 'get',
    params: {
      object: object,
      type: type
    }
  })
}

export function getObject (object) {
  return request({
    url: 'oss/get-object',
    method: 'get',
    params: {
      object: object
    }
  })
}

export function PostObject (file, policy, key, fileObject) {
  let form = new FormData()
  form.append('OSSAccessKeyId', policy.accessKeyId)
  form.append('policy', policy.policy)
  form.append('Signature', policy.signature)
  form.append('key', key)
  form.append('file', file)
  fileObject.progressVisible = true
  fileObject.progress = 0
  return request({
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    url: policy.host,
    method: 'post',
    data: form,
    onUploadProgress: function (progressEvent) {
      if (progressEvent.lengthComputable) {
        fileObject.progress = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
      }
    }
  })
}
export function PutObject (signedUrl, file) {
  /*
  return request({
    url: signedUrl,
    method: 'put',
    data: file
  })
  return request({
    url: signedUrl,
    method: 'put',
    data: '1234',
    header: {
      'Content-Length': 4
    }
  })*/
}

export function fileReader (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      resolve(reader.result)
    }
    reader.readAsBinaryString(file)
  })
}
